<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Config;

class Base extends \app\base\controller\Base
{
    public $passengerInfo;
    public $redisPreFix = 'jjcx.passenger.';

    public function _initialize()
    {
        // Redis缓存
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
        $this->dtoken = input('dtoken', '');//司机token
        $this->ptoken = input('ptoken','');//乘客token
        $this->requestMethod = Request::instance()->isPost(); //测试期间允许GET方便测试
        $this->dateTime = date('Y-m-d H:i:s');
        list($this->requestStatus, $this->requestMsg) = $this->checkRequest();
    }

    public function setRedis($key, $value)
    {
        $data = is_array($value) ? serialize($value) : $value;
        $this->redis->set($key, $data);
    }

    public function getRedis($key)
    {
        $value = $this->redis->get($key);
        $jsonData = unserialize($value);
        return (null === $jsonData) ? $value : $jsonData;
    }

    public function checkRequest()
    {
        if(!$this->requestMethod){
            return [3,103];
        }
        if(empty($this->dtoken)){
            return [0,101];
        }
        $this->passengerInfo = $this->getRedis($this->ptoken);
        $arr                 = explode('@',$this->ptoken);
        $passengerBase       = $arr[0].'*';
        $otherLogin          = $this->redis->keys($passengerBase);
        if(empty($this->passengerInfo) && !empty($otherLogin)){
            return [0,120];
        }
        if(empty($this->passengerInfo) || time() - $this->passengerInfo['activetime'] >Config::get('login_time_expire')){
            return [4,301];
        }
        $this->passengerInfo['activetime'] = time();
        $this->setRedis($this->dtoken,$this->passengerInfo);
        return [1,'ok'];
    }

    /**
     * 权限验证
     * @param int $code
     * @param string $msg
     */
    public function auth(){
        if($this->requestStatus==0){
            abort(0,$this->getErrorMsg($this->requestMsg));
        }
    }

    /**
     * 错误信息代码转换
     * @param int $code
     * @return string
     */
    public function getErrorMsg($code=100){
        $errorArr = \think\Config::get('error_msg');
        return isset($errorArr[$code]) ? $errorArr[$code] : 'undefine';
    }

    //登录获得token
    function CorePwd($pwd, $salt = '')
    {
        return md5(md5($pwd) . $salt);
    }

    //额外费用  远途费、夜间行驶费
    public function milesFee($cost_info, $miles)
    {
        $start_price = $cost_info['p_starting_price']; //起步费
        $now_time = date('Y-m-d H:i:s', time());

        //计算总费用
        //远途费 例：原1.7元/公里。超6公里后，每公里费用加0.8元，即1.7+0.8元/公里
        if ($miles > config('passenger.car_cost')['long_distance_km']) {

            $transit_cost = ($miles - config('passenger.car_cost')['long_distance_km']) * floatval($cost_info['p_transit_cost']); //远途费

        }

        //夜间服务费
        if ($now_time > config('passenger.car_cost')['night_start'] || $now_time < config('passenger.car_cost')['night_end']) {

            $night_cost = $miles * $cost_info['p_night_driving_cost'];
        }

        $all_cost = $start_price + $miles * $cost_info['p_mileage_cost'] + $transit_cost + $night_cost;

        return $all_cost;
    }

    //低速行驶 用时额外费用
    public function calLowFee($carDetail, $low_speed_time)
    {
        //低速费：低于12公里/小时，收0.4元/分钟
        $low_fee = ceil(floatval($low_speed_time) / 60.00) * floatval($carDetail['low_fee']);
        Log::record("low_speed_time $low_speed_time,$low_fee " . $carDetail['low_fee']);
        return $low_fee;
    }

    //侯客费用 超10分 开始
    public function calWaitFee($carDetail, $wait_start, $wait_end_time)
    {
        //候客费：司机到达目的地后，点击“到达目的地”，开始计算等待时间，
        //等待时间超过10分钟，收取0.5元/分钟
        if (empty($wait_start)) //没有等待
            return 0;
        $waitMin = ceil((strtotime($wait_end_time) - strtotime($wait_start)) / 60);
        $midMin = get_param_value('wait_min');
        if ($waitMin <= $midMin)
            return 0;

        $wait_fee = ($waitMin - $midMin) * floatval($carDetail['wait_fee']);
        return $wait_fee;
    }

    //获取随机4~8位数
    public function sj_rand()
    {
        $numbers = range(10, 99);
        //shuffle 将数组顺序随即打乱
        shuffle($numbers);
        //array_slice 取该数组中的某一段
        $num = 4;
        $result = array_slice($numbers, 0, $num);
        $sj = join("", $result);
        return $sj;
    }

    //返回提示
    public function msg_rtn($code, $msg = '')
    {
        $info['code'] = $code;
        $info['msg'] = $msg;
        return json($info);
    }

    //返回数据
    public function rtn_data($code, $msg)
    {

        $info['code'] = $code;
        $info['data'] = $msg;

        return json($info);
    }

}
